<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class User_c extends CI_Controller {
        public function __construct() {
            parent::__construct();
            $this->load->model(array('user_m', 'groups_m', 'role_m'));
            $this->load->helper(array('url', 'form', 'html'));
            $this->load->library(array('upload', 'form_validation', 'pagination', 'Datatables', 'table'));
        }
        
//        public function index() {
//            $data['title'] = 'User'; 
//            $data['error'] = $this->session->flashdata('error');
//            $data['success'] = $this->session->flashdata('success');
//            
//            $config = array();
//            $config["base_url"] = site_url('/user_c/index/');
//            $config["total_rows"] = sizeof($this->user_m->admin_user_records($this->session->userdata('idno')));
//            $config["per_page"] = 10;
//            $config["uri_segment"] = 3;
//            $config['full_tag_open'] = '<p id=page_link>';
//            $config['full_tag_close'] = '</p>';
//            $config['first_link'] = 'First';
//            $config['first_tag_open'] = '<span id=first_link>';
//            $config['first_tag_close'] = '</span>';
//            $config['last_link'] = 'Last';
//            $config['last_tag_open'] = '<span id=last_link>';
//            $config['last_tag_close'] = '</span>';
//            $config['prev_link'] = 'Previous';
//            $config['prev_tag_open'] = '<span id=prev_link>';
//            $config['prev_tag_close'] = '</span>';
//            $config['next_link'] = 'Next';
//            $config['nex_tag_open'] = '<span id=next_link>';
//            $config['next_tag_close'] = '</span>';
//
//            $this->pagination->initialize($config);
//            
//            
//            $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
//            $data["results"] = $this->user_m->fetch_users_asc($config["per_page"], $page, $this->session->userdata('idno'), 'idno');
//            $data["links"] = $this->pagination->create_links();
//            $data['segment'] = $this->uri->segment(4);
//        
//            $this->load->view('administrator/fragments/header_v', $data);
//            $this->load->view('administrator/fragments/user_navigation_v', $data);
//            $this->load->view('administrator/users_v', $data);
//            $this->load->view('administrator/fragments/footer_v', $data);
//        }
        
        public function index() {
            $data['title'] = 'User'; 
            $data['error'] = $this->session->flashdata('error');
            $data['success'] = $this->session->flashdata('success');
            
            $tmpl = array ( 'table_open'  => '<table id="big_table" class="mytable">' );
            $this->table->set_template($tmpl); 

            $this->table->set_heading('Register?', 'ID Number', 'First Name', 'Middle Name', 'Last Name', 'Email Address', 'Type', 'Course/Dept', 'Role', '');
        
            $this->load->view('administrator/fragments/header_v', $data);
            $this->load->view('administrator/fragments/user_navigation_v', $data);
            $this->load->view('administrator/users_v', $data);
            $this->load->view('administrator/fragments/footer_v', $data);
        }
        
        function datatable() {
            $this->datatables->select('department,idno,fname,mname,lname,email,type,course,rolename')
            ->from('user')
            ->join('user_role', 'user.user_id=user_role.user_id')
            ->join('role', 'user_role.role_id=role.role_id')
            ->where('status', 'active')
            ->edit_column('course', '$1$2', 'department, course')
            ->edit_column('department', '$1', 'idno')
            ->add_column('edit', '<a href="user/edit/$1">Edit</a>', 'idno');
            echo $this->datatables->generate();
        }
        
//        function sort_user($column ,$order, $segment){
//            $data['title'] = 'User'; 
//            $data['error'] = $this->session->flashdata('error');
//            $data['success'] = $this->session->flashdata('success');
//            
//            $config = array();
//            $config["base_url"] = site_url('/users/'.$this->uri->segment(3).'/'.$this->uri->segment(4).'/index/');
//            $config["total_rows"] = sizeof($this->user_m->admin_user_records($this->session->userdata('idno')));
//            $config["per_page"] = 5;
//            $config["uri_segment"] = 3;
//            $config['full_tag_open'] = '<p id=page_link>';
//            $config['full_tag_close'] = '</p>';
//            $config['first_link'] = 'First';
//            $config['first_tag_open'] = '<span id=first_link>';
//            $config['first_tag_close'] = '</span>';
//            $config['last_link'] = 'Last';
//            $config['last_tag_open'] = '<span id=last_link>';
//            $config['last_tag_close'] = '</span>';
//            $config['prev_link'] = 'Previous';
//            $config['prev_tag_open'] = '<span id=prev_link>';
//            $config['prev_tag_close'] = '</span>';
//            $config['next_link'] = 'Next';
//            $config['nex_tag_open'] = '<span id=next_link>';
//            $config['next_tag_close'] = '</span>';
//
//            $this->pagination->initialize($config);
//            
//            
//            $page = ($this->uri->segment(5)) ? $this->uri->segment(5) : 0;
//            #$data['segment'] = $this->uri->segment(5);
//            // arrow down and up was clicked
//            if($this->uri->segment(4) !== FALSE) {
//                if($this->uri->segment(4)==='DESC'){
//                    $data["results"] = $this->user_m->fetch_users_desc($config["per_page"], $page, $this->session->userdata('idno'), $this->uri->segment(3));
//                }else if($this->uri->segment(4)==='ASC') {
//                    $data["results"] = $this->user_m->fetch_users_asc($config["per_page"], $page, $this->session->userdata('idno'), $this->uri->segment(3));
//                }
//            }else if($this->uri->segment(3) !== FALSE){
//                if($this->uri->segment(3)==='DESC'){
//                    $data["results"] = $this->user_m->fetch_users_desc($config["per_page"], $page, $this->session->userdata('idno'), $this->uri->segment(2));
//                }else if($this->uri->segment(3)==='ASC') {
//                    $data["results"] = $this->user_m->fetch_users_asc($config["per_page"], $page, $this->session->userdata('idno'), $this->uri->segment(2));
//                }
//                
//            } else {
//                $data["results"] = $this->user_m->fetch_users_desc($config["per_page"], $page, $this->session->userdata('idno'), 'idno');
//            }
//            #$data["results"] = $this->user_m->fetch_users_asc($config["per_page"], $page, $this->session->userdata('idno'), 'idno');
//            $data["links"] = $this->pagination->create_links();
//            $data['segment'] = $this->uri->segment(4);
//        
//            $this->load->view('administrator/fragments/header_v', $data);
//            $this->load->view('administrator/fragments/user_navigation_v', $data);
//            $this->load->view('administrator/users_v', $data);
//            $this->load->view('administrator/fragments/footer_v', $data);
//        }
        
        function upload() {
            $data['title'] = 'Upload Students/Employees'; 
            $data['error'] = $this->session->flashdata('error');
            $data['success'] = $this->session->flashdata('success');
            $this->load->view('administrator/fragments/header_v', $data);
            $this->load->view('administrator/fragments/user_navigation_v', $data);
            $this->load->view('administrator/upload_stud_emp_v', $data);
            $this->load->view('administrator/fragments/footer_v', $data);
        }
        
        function upload_file() {
            if($_FILES['userfile']['name']!=""){
              $config['upload_path'] = './uploads/';
              $config['allowed_types'] = 'txt|csv'; 
  //            $config['max_size'] = '100';
  //            $config['max_width'] = '1024';
  //            $config['max_height'] = '768';
  //            $config['overwrite'] = FALSE; //If the file exists it will be saved with a progressive number appended

              $this->upload->initialize($config);

              if( ! $this->upload->do_upload()){
                  $this->session->set_flashdata('error',  $this->upload->display_errors('',''));
                  redirect(base_url().'users');
              } else {
                //If upload successful
                $file_name = $this->upload->file_name;
                
                $linesToAdd = file("./uploads/" .$file_name);
                $fp = fopen("./uploads/" .$file_name, 'w');
                if(!empty($_POST['student'])) {//student
                  fwrite($fp, "idno,fname,mname,lname,email,course,\n");
                } else {
                  fwrite($fp, "idno,fname,mname,lname,email,department,\n");
                }
                foreach($linesToAdd as $line) {
                    fwrite($fp,$line);
                }
                fclose($fp);
                
                
                $this->load->library('csvreader');
    
                $filePath = './uploads/' . $file_name;

                $data['csvData'] = $this->csvreader->parse_file($filePath);
                
                $data['error'] = $this->session->flashdata('error');
                $data['success'] = $this->session->flashdata('success');

                if(!empty($_POST['student'])) {//student
                    $data['title'] = 'Uploaded Students';
                    $this->load->view('administrator/fragments/header_v', $data);
                    $this->load->view('administrator/fragments/user_navigation_v', $data);
                    $this->load->view('administrator/uploaded_stud_v', $data);
                    $this->load->view('administrator/fragments/footer_v', $data);
                } else {
                    $data['title'] = 'Uploaded Employees';
                    $this->load->view('administrator/fragments/header_v', $data);
                    $this->load->view('administrator/fragments/user_navigation_v', $data);
                    $this->load->view('administrator/uploaded_emp_v', $data);
                    $this->load->view('administrator/fragments/footer_v', $data);
                }
              }
            } else {
              $this->session->set_flashdata('error',  'Please choose a file to upload.');
              redirect(base_url().'user/upload_file');
            }
        }
                
        function register_stud() {
            if (isset($_POST['user']) && sizeof($_POST['user'])) {
              $users = array();
              $x = 0;
              foreach ($_POST['user'] as $user)  {
                  $user = str_replace("???"," ",$user);
                  $value = explode(",", $user);
                  $users[$x] = $value;
                  $x++;
              }
                $this->user_m->insert_stud(FALSE, $users);
                $this->session->set_flashdata('success', 'Student/s Successfully Registered.');
                redirect(base_url().'user/upload_file');
            } else {
                $this->session->set_flashdata('error', 'You did not choose any account to register.');
                redirect(base_url().'user/upload_file');
            }
        }
                
        function register_emp() {
            if (isset($_POST['user']) && sizeof($_POST['user'])) {
              $users = array();
              $x = 0;
              foreach ($_POST['user'] as $user)  {
                  $user = str_replace("???"," ",$user);
                  $value = explode(",", $user);
                  $users[$x] = $value;
                  $x++;
              }
              $this->user_m->insert_emp(FALSE, $users);
                $this->session->set_flashdata('success', 'Employee/s Successfully Registered.');
                redirect(base_url().'user/upload_file');
            } else {
                $this->session->set_flashdata('error', 'You did not choose any account to register.');
                redirect(base_url().'users/upload_file', 'refresh');
            }
        }
        
        function view_reg_stud() {
            $data['title'] = 'Register Student';
            $data['error'] = $this->session->flashdata('error');
            $data['success'] = $this->session->flashdata('success');
            
            $this->load->view('administrator/fragments/header_v', $data);
            $this->load->view('administrator/fragments/user_navigation_v', $data);
            $this->load->view('administrator/register_stud_v', $data);
            $this->load->view('administrator/fragments/footer_v', $data);
        }
        
        function view_reg_admin() {
            $data['title'] = 'Register Administrator';
            $data['error'] = $this->session->flashdata('error');
            $data['success'] = $this->session->flashdata('success');
            
            $this->load->view('administrator/fragments/header_v', $data);
            $this->load->view('administrator/fragments/user_navigation_v', $data);
            $this->load->view('administrator/register_admin_v', $data);
            $this->load->view('administrator/fragments/footer_v', $data);
        }
        
        function view_reg_emp() {
            $data['title'] = 'Register Employee';
            $data['error'] = $this->session->flashdata('error');
            $data['success'] = $this->session->flashdata('success');
            
            $this->load->view('administrator/fragments/header_v', $data);
            $this->load->view('administrator/fragments/user_navigation_v', $data);
            $this->load->view('administrator/register_emp_v', $data);
            $this->load->view('administrator/fragments/footer_v', $data);
        }
        
        function reg_admin() {
            $data = array(); 
            $data['idno'] = $this->input->post('idno');
            $data['fname'] = $this->input->post('fname');
            $data['mname'] = $this->input->post('mname');
            $data['lname'] = $this->input->post('lname');
            $data['email'] = $this->input->post('email');
            $this->user_m->insert_admin($data);
            $this->session->set_flashdata('success', 'Administrator Successfully Registered.');
            redirect(base_url().'register/admin');
        }
        
        function reg_stud() {
            $data = array(); 
            $data['idno'] = $this->input->post('idno');
            $data['fname'] = $this->input->post('fname');
            $data['mname'] = $this->input->post('mname');
            $data['lname'] = $this->input->post('lname');
            $data['email'] = $this->input->post('email');
            $data['course'] = $this->input->post('course');
            $this->user_m->insert_stud(TRUE, $data);
            $this->session->set_flashdata('success', 'Student Successfully Registered.');
            redirect(base_url().'register/stud');
        }
        
        function reg_emp() {
            $data = array(); 
            $data['idno'] = $this->input->post('idno');
            $data['fname'] = $this->input->post('fname');
            $data['mname'] = $this->input->post('mname');
            $data['lname'] = $this->input->post('lname');
            $data['email'] = $this->input->post('email');
            $data['dept'] = $this->input->post('dept');
            $this->user_m->insert_emp(TRUE, $data);
            $this->session->set_flashdata('success', 'Employee Successfully Registered.');
            redirect(base_url().'register/emp');
        }
        
        function edit_user($idno) {
            $data['user'] = $this->user_m->get_user($idno);
            $temp = $this->user_m->get_user($idno);
            $data['error'] = $this->session->flashdata('error');
            $data['success'] = $this->session->flashdata('success');
            $data['title'] = 'Edit User';
            
            $this->form_validation->set_rules('fname', 'First Name', 'required|xss_clean');
            $this->form_validation->set_rules('mname', 'Middle Name', 'required|xss_clean');
            $this->form_validation->set_rules('lname', 'Last Name', 'required|xss_clean');
            $this->form_validation->set_rules('email', 'Email Address', 'required|xss_clean');
            $this->form_validation->set_rules('cd', 'Course/Department', 'required|xss_clean');
            
            if(isset($_POST) && !empty($_POST)) {
                if(isset($_POST['resetpass'])) {
                    $reset = $this->user_m->reset_password($idno, $this->input->post('email'));
                    if($reset) {
                        $this->session->set_flashdata('success',  'Password was successfully reset.');
                        redirect(base_url().'users');
                    } else {
                        $this->session->set_flashdata('error',  'An unknown error has occurred. Please check the email address if it is valid.');
                        redirect(base_url().'users');
                    }
                }else {
                  if(!is_null($temp['course'])) {
                    $info = array(
                        'idno' => $idno,
                        'fname' => $this->input->post('fname'),
                        'mname' => $this->input->post('mname'),
                        'lname' => $this->input->post('lname'),
                        'email' => $this->input->post('email'),
                        'course' => $this->input->post('cd'),
                        'password' => NULL
                    );
                  } else if(!is_null($temp['department'])) {
                    $info = array(
                        'idno' => $idno,
                        'fname' => $this->input->post('fname'),
                        'mname' => $this->input->post('mname'),
                        'lname' => $this->input->post('lname'),
                        'email' => $this->input->post('email'),
                        'department' => $this->input->post('cd'),
                        'password' => NULL
                    );
                  } else {
                    $info = array(
                        'idno' => $idno,
                        'fname' => $this->input->post('fname'),
                        'mname' => $this->input->post('mname'),
                        'lname' => $this->input->post('lname'),
                        'email' => $this->input->post('email'),
                        'password' => NULL
                    );
                  }
                    
                    if ($this->form_validation->run() === TRUE) {

                        $this->session->set_flashdata('success', 'User successfully updated.');
                        $this->user_m->update_user($info);
                        redirect(base_url().'users');
                    } 
                }
                
            }
            
            $this->load->view('administrator/fragments/header_v', $data);
            $this->load->view('administrator/fragments/user_navigation_v', $data);
            $this->load->view('administrator/edit_user_v', $data);
            $this->load->view('administrator/fragments/footer_v', $data);
        }
        
        function delete_user($user_id) {
            $this->user_m->delete_user($user_id);
            
            $this->session->set_flashdata('success', 'User successfully deleted.');
            
            redirect(base_url().'users');
        }
                
        function delete_user_update_role() {
            if(!empty($_POST['deleteB'])) {//delete
              if (isset($_POST['user']) && !empty($_POST)) {
                foreach ($_POST['user'] as $idno)  {
                  $user = $this->user_m->get_user_id($idno);
                  $this->user_m->delete_user($user->user_id);
                }
                $this->session->set_flashdata('success', 'User/s successfully deleted.');
                redirect(base_url().'users');
              } else {
                  $this->session->set_flashdata('error', 'You did not check any user to delete!');
                  redirect(base_url().'users');
              }
            } else {//update role
              $role_id = $_POST['role'];
              if (isset($_POST['user']) && !empty($_POST)) {
                  if(!is_null($role_id)) {
                      foreach ($_POST['user'] as $idno)  {
                        $user = $this->user_m->get_user_id($idno);
                        $this->user_m->update_user_role($user->user_id, $role_id);
                      }
                      $this->session->set_flashdata('success', 'Role successfully updated.');
                      redirect(base_url().'users');
                  } else {
                      $this->session->set_flashdata('error', 'You did not select a role!');
                      redirect(base_url().'users');
                  }
              } else {
                  $this->session->set_flashdata('error', 'You did not check any user to update!');
                  redirect(base_url().'users');
              }
            }
        }
    }
?>